import requests
import random
from time import sleep

# 代理的全局变量
proxy = None
usenum = random.randint(3,5)

# 获取代理
def get_proxy(isUse=True):
    '''获取代理地址，参数说明当前代理是否可用'''
    global usenum, proxy
    if not isUse:
        # 如果当前代理不可用，通知服务器删除代理信息
        requests.get("http://127.0.0.1:5010/delete/?proxy={}".format(proxy))
        proxy = None

    # 确保每个代理被使用几次后才更换
    if usenum > 0:
        usenum -= 1
        print(f"使用代理[{usenum}]: {proxy}")
    
    # 获取新的代理
    resp_json = requests.get("http://127.0.0.1:5010/get/?type=https").json()
    proxy = resp_json.get("proxy")
    usenum = random.randint(3,6)
    print(f"使用代理[{usenum}]: {proxy}")

# 获取列表数据
def get_list(param):
    '''获取列表数据'''
    try:
        headers={
            "Accept":"application/json, text/plain, */*",
            "Content-Type":"application/json",
            "Origin":"https://www.XXXX.com",
            "Referer":"https://www.XXXX.com/",
            "Connection": "keep-alive",
            "Host":"api.XXXX.com",
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36 Edg/120.0.0.0",
            "sec-ch-ua-platform": "Windows",
            "Sec-Fetch-Site": "same-site"
        }
        print(f"开始请求getlist：")
        get_proxy()
        resp = requests.post('https://api.XXXX.com/list', verify=False, proxies={"https": "https://{}".format(proxy)}, headers=headers, json=param)
        print(resp.status_code)
        data = resp.json()
        dataList = []
        if data.code == 200:
            dataList = data.data.list
        # 查看响应内容，response.text 返回的是Unicode格式的数据
        print(dataList)
        # 使用代理访问
        return dataList
    except Exception as ex:
        print(f"错误：{ex}")

if __name__ == '__main__':
    '''直接运行时的操作'''
    param = {
        "pageNum":1,
        "pageSize":10,
        "startDate":"2023-12-20 00:00:00",
        "endDate":"2023-12-31 23:59:59",
    }
    list = get_list(param)

    sleep(random(2,6))